package registry

import (
	"awesomeTask/application/variable"
	"awesomeTask/commom/KeyHelper"
	"awesomeTask/config"
	"awesomeTask/system/helper"
	"awesomeTask/system/safe"
	"errors"
	"net"
	"strconv"
)

var nodesRocords map[string]map[string]interface{}
var nodesRecordsPath string = config.GetConfigByKey("workPath").(string) + "/FileSystem/nodesRecords.json"

func RecordNode(ipAddress string, port int, uniqueId string) {
	initRecords()
	safe.Lock()
	key := ipAddress + ":" + strconv.Itoa(port)
	_, ok := nodesRocords[key]
	if ok == false || (ok == true && nodesRocords[key]["uniqueId"] == nil) {
		nodesRocords[key] = map[string]interface{}{
			"ipAddress": ipAddress,
			"port":      port,
			"uniqueId":  uniqueId,
		}
		storeRecords()
	}
	safe.Unlock()
}

/**
获取连接节点更加uniqueID
*/
func GetConnectionByUniqueId(uniqueId string) (net.Conn, error) {
	for _, value := range nodesRocords {
		if value["uniqueId"] == uniqueId {
			con, ok := variable.ServerConnections.Load(KeyHelper.TcpUniqueId(value["ipAddress"].(string), value["port"].(int)))
			if ok {
				return con.(net.Conn), nil
			}
		}
	}
	return nil, errors.New("未连接到此节点")
}
func ForgetNodes(ipAddress string, port int) {
	initRecords()
	safe.Lock()
	key := ipAddress + strconv.Itoa(port)
	_, ok := nodesRocords[key]
	if ok == false {
		delete(nodesRocords, key)
		storeRecords()
	}
	safe.Unlock()
}
func GetDisConnections() map[string]map[string]interface{} {
	initRecords()
	res := make(map[string]map[string]interface{})
	for key, item := range nodesRocords {
		_, ok := variable.ServerConnections.Load(key)
		if ok == false {
			res[key] = item
		}
	}
	return res
}
func initRecords() {
	if nodesRocords == nil {
		safe.Lock()
		if helper.CheckFileIsExist(nodesRecordsPath) == false {
			nodesRocords = map[string]map[string]interface{}{}
		} else {
			nodesRocords = map[string]map[string]interface{}{}
			res := helper.JsonDecode(helper.ReadFileAsString(nodesRecordsPath)).(map[string]interface{})
			for key, item := range res {
				nodesRocords[key] = item.(map[string]interface{})
			}
		}
		configJson := config.InitConfig()
		managerConfig := configJson["node"].(map[string]interface{})["manager"].(map[string]interface{})
		port, _ := strconv.Atoi(managerConfig["port"].(string))
		nodesRocords[KeyHelper.TcpUniqueId("127.0.0.1", int(config.GetConfigByKey("listenPort").(float64)))] = map[string]interface{}{
			"ipAddress": config.GetConfigByKey("listenIpAddress").(string),
			"port":      config.GetConfigByKey("listenPort"),
		}
		nodesRocords[KeyHelper.TcpUniqueId(managerConfig["ipAddress"].(string), port)] = map[string]interface{}{
			"ipAddress": managerConfig["ipAddress"].(string),
			"port":      port,
		}
		storeRecords()
		safe.Unlock()
	}
}
func storeRecords() {
	initRecords()
	helper.WriteFile(nodesRecordsPath, helper.FormatJsonStringfy(nodesRocords), 0777)
}
